/*
 * $Id$
 */
package py.firefly.request;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import static py.firefly.resolution.Tiles.TILES;

/**
 *
 * @author myang
 */
public class HttpRequest implements Request {

    private final HttpServletRequest _req;

    private final String _uri;

    private final RequestParameters _params = new Parameters();

    public HttpRequest(final HttpServletRequest req) {
        _req = req;
        _uri = decodeURI();
        attr(TILES, Collections.<String, Object>emptyMap());
    }

    private String decodeURI() {
        final String s = _req.getRequestURI();
        try {
            return URLDecoder.decode(s, "UTF-8");
        } 
        catch (final UnsupportedEncodingException ex) {
        }
        return s;
    }

    @Override
    public boolean is(final HttpMethod method) {
        return HttpMethod.valueOf(_req.getMethod()) == method;
    }

    @Override
    public String path() {
        return _req.getPathInfo();
    }

    @Override
    public RequestParameters params() {
        return _params;
    }

    @Override
    public HttpServletRequest containerRequest() {
        return _req;
    }

    @Override
    public void forward(final String path, final Response resp) {
        try {
            _req.getRequestDispatcher(path)
                    .forward(_req, resp.containerResponse());
        } catch (final Exception ex) {
        }
    }

    @Override
    public String uri() {
        return _uri;
    }

    @Override
    public HttpRequest attr(final String name, final Object val) {
        _req.setAttribute(name, val);
        return this;
    }

    @Override
    public Object attr(final String name) {
        return _req.getAttribute(name);
    }

    @Override
    public Object context(final String name) {
        return _req.getSession().getServletContext().getAttribute(name);
    }

    /**
     * 
     */
    class Parameters implements RequestParameters {

        private Map<String, Object> _params = new HashMap();    

        @Override
        public RequestParameters add(final Map<String, String> vals) {
            _params.putAll(vals);
            return this;
        }

        @Override
        public String get(final String name) {
            final String val = _req.getParameter(name);
            return null == val ? (String)_params.get(name) : val;
        }

        @Override
        public int getInt(final String name) {
            return Integer.parseInt(get(name));
        }
    }

   
}
